package com.ys.peony.utils;

import android.content.Context;
import android.os.Looper;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;

public class CrashHandler implements UncaughtExceptionHandler {

    private static CrashHandler             INSTANCE = new CrashHandler ();
    private Context                         mContext;
    private UncaughtExceptionHandler mDefaultHandler;

    private CrashHandler() {}

    public static CrashHandler getInstance(){
        return INSTANCE;
    }

    public void init(Context ctx){
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler ();
        Thread.setDefaultUncaughtExceptionHandler (this);
    }

    /**
     * 捕获未处理的异常信息
     */
    @Override
    public void uncaughtException(Thread thread,Throwable ex){

        final Throwable eex = ex;
        new Thread () {

            @Override
            public void run(){
                ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
                PrintStream ps = new PrintStream (outStream);
                eex.printStackTrace (ps);
                String Stack = outStream.toString ();
                // ToolUtils.showmsg(mContext, "应用崩溃 全局异常处理");
                // FileManager.saveError("异常",ex.toString()+"\r\n"+Stack);
                FileManager.saveLog (eex.toString () + "\r\n" + Stack);
                android.os.Process.killProcess (android.os.Process.myPid ());
                System.exit (10);
            }
        }.start ();

    }

    /** 
    * 可以根据自己的情况来自定义异常处理逻辑 
    * 
    * @param ex 
    * @return true:如果处理了该异常信息;否则返回false 
    */
    private boolean handleException(Throwable ex){
        if (ex == null) { return false; }

        final Throwable eex = ex;
        new Thread () {

            @Override
            public void run(){
                Looper.prepare ();
                // new AlertDialog.Builder(mContext).setTitle("崩了").setCancelable(false).setMessage("程序崩溃�?").setNegativeButton("确定�?�?", new DialogInterface.OnClickListener()
                // {
                // @Override
                // public void onClick(DialogInterface dialog, int which)
                // {
                ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
                PrintStream ps = new PrintStream (outStream);
                eex.printStackTrace (ps);
                String Stack = outStream.toString ();
                // ToolUtils.showmsg(mContext, "应用崩溃 全局异常处理");
                // FileManager.saveError("异常",ex.toString()+"\r\n"+Stack);
                FileManager.saveLog (eex.toString () + "\r\n" + Stack);
                android.os.Process.killProcess (android.os.Process.myPid ());
                System.exit (10);
                // }
                // }).create().show();

                Looper.loop ();
            }
        }.start ();

        return true;
    }

}
